define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        config = require("./setting"),
        method = require("./method");
    $(function() {
        var $scroll = $('.no-touch .slim-scroll');
        $scroll.length > 0 && require.async(['slimscroll'], function() {
            $scroll.each(function() {

                var $self = $(this),
                    $data = $self.data(),
                    $slimResize;
                $self.slimScroll($data);
                $(window).resize(function(e) {
                    clearTimeout($slimResize);
                    $slimResize = setTimeout(function() {
                        $self.slimScroll($data);
                    }, 500);
                })
            })
        })

    });


    $.fn.addAttr = function(ar, flag) {
        return this.each(function() {
            var self = $(this);
            if (flag) {
                self.attr(ar, ar);
            } else {
                self.removeAttr(ar);
            }
        });
    };
    $.fn.adddClass = function(ar, flag) {
        return this.each(function() {
            var self = $(this);
            if (flag) {
                self.addClass(ar);
            }
        });
    };
    $.fn.addhtml = function(html, flag) {
        return this.each(function() {
            var self = $(this);
            if (flag) {
                self.append(html)
            } else {
                self.prepend(html);
            }
        });
    };
    $.fn.append2 = function(html, callback) {
        var originalHtmlLength = $("body").html().length;
        this.append(html);
        var nums = 1;
        var timer1 = setInterval(function() {
            nums++;
            var clearIntervalfun = function() {
                clearInterval(timer1)
                callback();
            }
           

            var flag = originalHtmlLength != $("body").html().length || nums > 1000;
            // console.info("append html expend {0}ms".format(nums))
            flag && clearIntervalfun()

        }, 1)
    };
    ! function($) {
        var pnode = function(item, options) {
           
            return options || (options = {}), {
                id: item.id,
                parent: item.parentid || "#",
                text: item.name,
                state: {
                    opened: options.selected ? item.id == options.selected || (options.selected == -1 && 0 == item.parentid) : 0 == item.parentid,
                    disabled: item.is_readonly,
                    selected: $.inArray(item.id, options.selected) > -1
                },
                wid:item.wid
            }
        };
        var ptoke = function(item, options) { 
            options || (options = {});
            var obj={
                id: item.id,
                name: item.name,
                keywords: [item.name, item.pinyinname],
                wid:item.wid,
                readonly: options.readonly
            };
            item.name&&obj.keywords.push(item.name);
            item.pinyinname&&obj.keywords.push(item.pinyinname); 
            return options,obj;
        }
        var mtoke = function(item, options) { 
            options || (options = {});
            var obj={
                id: config.membersp + item.id,
                name: item.username,
                username:item.username,
                keywords: [],
                thumb_path: item.thumb_path,
                readonly: options.readonly,
                JoinStatus: item.JoinStatus
            };
            item.username&&obj.keywords.push(item.username);
            item.pinyinname&&obj.keywords.push(item.pinyinname);
            item.bizmpid&&obj.keywords.push(item.bizmpid); 
            return options,obj;
        }
        $.tokenInputConverter = {
            party2node: function(item, options) {
                return pnode(item, options)
            },
            forparty2node: function(data, options) {
                var d = []; 
                $.each(data, function(index, item) {
                    d.push(pnode(item, options));
                });
                return d;
            },
            party2token: function() {
                return ptoke(item, options)
            },
            forparty2token: function(data, options) {
                var d = [];
                $.each(data, function(index, item) {
                    d.push(ptoke(item, options));
                });
                return d;
            },
            member2token: function(data, options) {
                return mtoke(data, options)
            },
            formember2token: function(data, options) {
                var d = [];
                $.each(data, function(index, item) {
                    d.push(mtoke(item, options));
                }); 
                return d;
            },
            membersForValue: function(c) {
                var d = c.split(","),
                    e = [];
                return a.each(d, function(a, c) {
                    c && c[0] != b && e.push(c)
                }), e
            },
            partiesForValue: function(c) {
                var d = c.split(","),
                    e = [];
                return a.each(d, function(a, c) {
                    c && c[0] == b && e.push(c.substr(1))
                }), e
            }
        }
    }(jQuery)



    !(function($) {
        var HTML_ESCAPES = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#x27;',
            '/': '&#x2F;'
        };

        var HTML_ESCAPE_CHARS = /[&<>"'\/]/g;

        function _escapeHTML(text) {
            return text.replace(HTML_ESCAPE_CHARS, function(match) {
                return HTML_ESCAPES[match];
            });
        }

        var methods = {
            init: function(tokendata, jstreedata, options, selected) {
                var $this = this,org=$this.data("organization");
                var jstree_init = function(dropdown) {
                    if (!$this.data("jstree")) {
                        var js_tree_el = $('<div class="token-input-jstree">token-input-jstree</div>').appendTo(dropdown).on("select_node.jstree", function(e, data) {
                            $this.data("tokeninput").tokenInput("add", {
                                id: data.node.id,
                                name: data.node.text,
                                wid:data.node.wid
                            })
                        });
                        js_tree_el.jstree({
                            core: {
                                themes: {
                                    name: false,
                                    url: false,
                                    dir: false,
                                    icons: true,
                                    variant: false,
                                    stripes: false,
                                    responsive: true,
                                    dots: true
                                },
                                data: jstreedata
                            },
                            types: {
                                'default': {
                                    'icon': 'icon icon_folder_blue'
                                }
                            },
                            plugins: ["wholerow", "types"]
                        });
                        $this.data("jstree", js_tree_el);

                    }
                }

                var member_resultsFormatter = function(item) {
                    var id = item.id.toString(),
                        name = item.name;
                    if (id[0] == config.membersp) {
                        return "<li><img src='" + item.thumb_path + "' style='float:left;width:26px;height:26px;margin-right:6px'><span>" + (this.enableHTML ? name : _escapeHTML(name)) + "</span></li>"

                    } else {
                        return "<li><i style='color:#C9DDF6;' class='fa fa-folder m-r-xs'></i>" + (this.enableHTML ? name : _escapeHTML(name)) + "</li>";
                    }
                }
                var member_tokenFormatter = function(item) {
                    var id = item.id.toString(),
                        name = item.name;
                    if (id[0] == config.membersp) {
                        return "<li><img src='" + item.thumb_path + "' style='float:left;width:26px;height:26px'><p class='group_item_name'>" + (this.enableHTML ? name : _escapeHTML(name)) + "</p></li>"

                    } else {
                        return "<li><p class='group_item_name'><i style='color:#6EA6E7;' class='fa fa-folder m-r-xs'></i>" + (this.enableHTML ? name : _escapeHTML(name)) + "</p></li>";
                    }
                }
                var defaults = {
                    propertyToSearch: "keywords",
                    searchDelay: 50,
                    searchingText: null,
                    resultsLimit: 20,
                    excludeCurrent: true,
                    preventDuplicates: true,
                    animateDropdown: false,
                    hintText:org?"输入搜索条件":(jstreedata && jstreedata.length ? jstree_init : "输入成员名称"),
                    resultsFormatter: member_resultsFormatter,
                    tokenFormatter: member_tokenFormatter
                };

                options = $.extend({}, defaults, options);
                var tokenInput = $this.tokenInput(tokendata, options);
                if (selected) {
                    $.each(jstreedata, function(index, item) {
                        if ($.inArray(item.id, selected) > -1) {
                            tokenInput.tokenInput("add", {
                                id: item.id.toString(),
                                name: item.text,
                                wid:item.wid
                            })
                        }
                    });
                }
                $this.data("tokeninput", tokenInput)
            },
            destroy: function() {
                this.data("jstree") && (this.data("jstree").jstree().destroy(), this.removeData("jstree")), this.data("tokeninput") && (this.data("tokeninput").tokenInput("destroy"), this.removeData("tokeninput"))
            },
            addtoken: function(data) {

            }
        }
        $.fn.tokenInputTree = function(t) {
            return methods[t] ? methods[t].apply(this, Array.prototype.slice.call(arguments, 1)) : methods.init.apply(this, arguments)
        }

    })(jQuery)

    !(function($) {



        var scrollPage = function(options, callback, element) {
            this.element = $(element);
            this.init(options, callback);
            this.perform = false;
        }
        scrollPage.defaults = {
            selector: null,
            bufferPx: 30,
            appendElement: null,
            state: {
                is_continue: 1,
                currPage: 1
            },
            data: {},
            path: null
        }
        scrollPage.prototype = {
            init: function(options, callback) {
                this.options = $.extend(true, {}, scrollPage.defaults, options);
                var _self = this;

                this.element.on("scroll", function() {

                    if (_self.is_continue()) {
                        _self.beginAjax(_self.element, callback)
                    }
                })
                _self.beginAjax(_self.element, callback)
            },
            selector: function() {
                return $(this.options.selector)
            },
            is_continue: function() {
                var selector = this.selector();
                if (selector.length) {
                    return !this.perform && this.options.state.is_continue && selector.offset().top + this.options.bufferPx < $(window).height();
                } else {
                    return false;
                }

            },
            beginAjax: function(element, callback) {
                var _self = this;
                _self.perform = true;
                var data = $.extend(true, {
                    page: this.options.state.currPage
                }, this.options.data);
                $.ajax({
                    dataType: 'json',
                    type: 'GET',
                    data: data,
                    url: this.options.path
                }).done(function(result) {
                    callback(element, result);
                }).fail(function() {
                    config.msg.info(config.lang.exception);
                }).always(function() {
                    _self.options.state.currPage++;
                    _self.perform = false;
                    // if (_self.is_continue()) {
                    //     _self.beginAjax(element, callback)
                    // };
                })
            },
            update: function(options) {
                if ($.isPlainObject(options)) {
                    this.options = $.extend(true, this.options, options);
                }
            },
            destroy: function() {
                this.element.unbind('scroll');
                this.element.removeData("scrollPage");
            },
            toggleDone: function(flag) {
                this.options.state.is_continue = flag;
            }
        }
        $.fn.scrollPage = function(options, callback) {

            var thisCall = typeof options;
            if (thisCall === "string") {
                var args = Array.prototype.slice.call(arguments, 1);
                this.each(function() {
                    var instance = $.data(this, 'scrollPage');
                    if (!instance) {
                        return false;
                    }
                    if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
                        return false;
                    }
                    instance[options].apply(instance, args);
                });
            } else {
                this.each(function() {
                    var instance = $.data(this, 'scrollPage');
                    if (instance) {
                        instance.update(options);
                    } else {
                        instance = new scrollPage(options, callback, this);
                        $.data(this, 'scrollPage', instance);
                    }


                })
            }

        }
    })(jQuery)

    !(function($) {



        var uploader = function(options, defaults_file_type, element) {
            this.element = element.get(0);
            this.defaults_file_type = defaults_file_type;
            this.init(options);
        };
        uploader.defaults = {
            url: config.empty,
            multi: false, //是否多选
            prevent_duplicates: false, //文件不能重复
            mime_types: [], //文件类型
            max_file_size: 0, //文件大小
            data: {}, //附带参数
            max_count: 0, //一次最多上传
            max_count_tips:0,
            extensions:"",
            dropElement: "",
            FilesAdded: function() {
                //添加文件后触发的函数
            },
            UploadProgress: function() {
                //进度条
            },
            FileUploaded: function() {
                //上传完成
            },
            UploadComplete: function() {
                //全部上传完成
            }
        }
        uploader.prototype = {
            init: function(options) {
                var _self = this;
                if (this.defaults_file_type) {
                    switch (this.defaults_file_type) {
                        case "picture":
                            uploader.defaults.max_file_size = "2mb";
                            uploader.defaults.mime_types = [{
                                title: "图片文件",
                                extensions: "bmp,png,jpeg,jpg,gif"
                            }, ];
                            plupload.addI18n({
                                "File extension error.": "图片格式必须为以下格式：bmp, jpeg, jpg, gif",
                                "File size error.": "文件大小错误。",
                            });
                            break;
                        case "voice":
                            uploader.defaults.max_file_size = "5mb";
                            uploader.defaults.mime_types = [{
                                title: "音频文件",
                                extensions: "mp3,wma,wav,amr"
                            }, ];
                            plupload.addI18n({
                                "File extension error.": "语音格式必须为以下格式：mp3, wma, wav, amr"
                            });
                            break;
                        case "video":
                            uploader.defaults.max_file_size = "20mb";
                            uploader.defaults.mime_types = [{
                                title: "视频文件",
                                extensions: "rm,rmvb,wmv,avi,mpg,mpeg,mp4"
                            }, ];
                            plupload.addI18n({
                                "File extension error.": "视频格式必须为以下格式：rm, rmvb, wmv, avi, mpg, mpeg, mp4"
                            });
                            break;
                        case "file":
                            uploader.defaults.max_file_size = "10mb";
                            uploader.defaults.mime_types = [{
                                title: "自定义文件",
                                extensions: "txt,xml,pdf,zip,doc,ppt,xls,docx,pptx,xlsx"
                            }, ];
                            plupload.addI18n({
                                "File extension error.": "文件格式必须为以下格式：txt, xml, pdf, zip, doc, ppt, xls, docx, pptx, xlsx"
                            });
                            break;
                        case "other":
                            uploader.defaults.max_file_size = options.max_file_size;
                            uploader.defaults.mime_types = [{
                                title: "自定义文件",
                                extensions: ''+options.extensions+''
                            }, ];
                            plupload.addI18n({
                                "File extension error.": "文件格式必须为以下格式：{0}".format(options.extensions)
                            });
                            break;
                    }
                    plupload.addI18n({
                        "File size error.": "最大只能上传{0}的文件".format(uploader.defaults.max_file_size),
                    });
                };
                this.options = $.extend(true, {}, uploader.defaults, options);
                this.plupload = new plupload.Uploader({
                    runtimes: 'html5,flash,silverlight,html4',
                    browse_button: _self.element,
                    url: _self.options.url,
                    drop_element:_self.options.dropElement,
                    flash_swf_url: '/assets/swf/Moxie.swf',
                    silverlight_xap_url: '/assets/swf/Moxie.xap',
                    multi_selection: _self.options.multi,
                    filters: {
                        max_file_size: _self.options.max_file_size,
                        prevent_duplicates: _self.options.prevent_duplicates,
                        mime_types: _self.options.mime_types
                    },
                    multipart_params: _self.options.data,
                    init: {
                        FilesAdded: function(up, files) {
                            if (_self.options.max_count) {
                                if (up.files.length > _self.options.max_count) {
                                    if(_self.options.max_count_tips){
                                        config.msg.info("最多上传{0}个文件".format(_self.options.max_count_tips));
                                    }else{
                                        config.msg.info("最多上传{0}个文件".format(_self.options.max_count));
                                    }
                                    plupload.each(files, function(file) {
                                        up.removeFile(file);

                                    });
                                    return false;
                                }
                            };
                            _self.options.FilesAdded(up, files);
                            up.start();
                        },
                        UploadProgress: function(up, file) {
                            _self.options.UploadProgress(up, file);
                        },
                        UploadComplete: function(up, file) {
                            _self.options.UploadComplete(up, file);
                        },
                        FileUploaded: function(up, file, res) {
                            _self.options.FileUploaded(up, file, $.parseJSON(res.response));
                        },
                        Error: function(up, err) {
                            config.msg.info(err.message); //待优化
                            return false;
                        }
                    }
                })
                this.plupload.init();

            },
            update: function(options) {
                if ($.isPlainObject(options)) {
                    this.options = $.extend(true, this.options, options);
                }
            },
            destroy: function() {
                this.plupload.destroy();
                this.element.removeData("uploader");
            }

        }
        $.fn.uploader = function(options, defaults_file_type) {
            var _self = this,farguments=arguments;
            require.async(['plupload'], function() {
                var thisCall = typeof options;
                if (thisCall === "string") {
                    var args = Array.prototype.slice.call(farguments, 1);
                    _self.each(function() {
                        var instance = $.data(_self, 'uploader');
                        console.log(instance)
                        if (!instance) {
                            return false;
                        }
                        if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
                            return false;
                        }
                        instance[options].apply(instance, args);
                    });
                } else {
                    _self.each(function() {
                        var instance = $.data(_self, 'uploader');
                        if (instance) {
                            instance.update(options);
                        } else {
                            instance = new uploader(options, defaults_file_type, _self);
                            $.data(_self, 'uploader', instance);
                        }
                    })

                }
            })
        }
    })(jQuery)

    // $(".message_block").scrollPage({
    //     selector: "li.item:last",
    //     path: "/api/Files/list?type=1&count=40&page=3"
    // }, function(element,result) {
    //     element.scrollPage("toggleDone",result.is_is_continue);
    //     if (result.last_file_item) {
    //         var data={
    //             title="最近",
    //             file_items:result.file_items,
    //             update_time:result.update_time
    //         }
    //     };

    //     // $(".js_audio_container")
    // })
    // $(".message_block").scrollPage("update",{state:{
    //      isDone: true
    // }})
    // $(".message_block").on("scroll",function  () {
    //     var item=$("li.item:last");
    //     console.log("item："+item.offset().top)
    //       console.log("window"+$(window).height())
    //     console.log( item.offset().top+30 < $(window).height())
    // })









    !(function($) {



        $.fn.setCursorPosition = function(position) {
            if (this.lengh == 0) return this;
            return $(this).setSelection(position, position);
        }

        $.fn.setSelection = function(selectionStart, selectionEnd) {
            if (this.lengh == 0) return this;
            var input = this[0];

            if (input.createTextRange) {
                var range = input.createTextRange();
                range.collapse(true);
                range.moveEnd('character', selectionEnd);
                range.moveStart('character', selectionStart);
                range.select();
            } else if (input.setSelectionRange) {
                input.focus();
                input.setSelectionRange(selectionStart, selectionEnd);
            }

            return this;
        }

        $.fn.focusEnd = function() {
            this.setCursorPosition(this.val().length);
        }

    })(jQuery)


    !(function($) {


        $.fn.ajaxfile = function(options, callback) {
            var $this = $(this);
            require.async('ajaxfileupload', function() {
                $this.on("click", function() {
                    var $input = $this.find(":file"),
                        $button = $this.find(".btn"),
                        data = $this.data();
                    $button.data("loadingText", '<i class="fa fa-spinner fa-spin"></i>上传中')
                    $input.on("change", function(e) {
                        var n = e.target.files !== undefined ? e.target.files[0] : e.target.value ? {
                            name: e.target.value.replace(/^.+\\/, "")
                        } : null;
                        var upfile = function(callback) {
                            $button.button('loading');
                            jQuery.ajaxFileUpload({
                                url: options.path,
                                secureuri: false,
                                dataType: 'json',
                                fileElement: $input,
                                data: options.data,
                                success: function(d, status) {
                                    callback(d)
                                    $button.button('reset');
                                },
                                error: function(data, status, ex) {
                                    console.log(data)
                                    $button.button('reset');
                                    config.msg.info("上传文件错误，请重新上传。");
                                    return false;
                                }
                            });
                        }
                        if (n.name) {
                            if (data.type) {
                                switch (data.type) {
                                    case "img":
                                        if (!/(.*)\.(jpg|gif|jpeg|png|bmp)$/i.test(n.name)) {
                                            config.msg.info("请上传jpg、gif、jpeg、png或bmp格式的图片。");
                                            return false;
                                        }
                                        upfile(function(d) {
                                            callback(d)
                                        })
                                        break;
                                }
                            } else {
                                console.error("输入类型");
                            }
                        }

                    })
                })
            })

        }
    })(jQuery)




    jQuery.extend({
        /**
         * 清除当前选择内容
         */
        unselectContents: function() {
            if (window.getSelection) window.getSelection().removeAllRanges();
            else if (document.selection) document.selection.empty();
        }
    });
    jQuery.fn.extend({
        /**
         * 选中内容
         */
        selectContents: function() {
            $(this).each(function(i) {
                var node = this;
                var selection, range, doc, win;
                if ((doc = node.ownerDocument) && (win = doc.defaultView) && typeof win.getSelection != 'undefined' && typeof doc.createRange != 'undefined' && (selection = window.getSelection()) && typeof selection.removeAllRanges != 'undefined') {
                    range = doc.createRange();
                    range.selectNode(node);
                    if (i == 0) {
                        selection.removeAllRanges();
                    }
                    selection.addRange(range);
                } else if (document.body && typeof document.body.createTextRange != 'undefined' && (range = document.body.createTextRange())) {
                    range.moveToElementText(node);
                    range.select();
                }
            });
        },
        /**
         * 初始化对象以支持光标处插入内容
         */
        setCaret: function() {
            if (!$.browser.msie) return;
            var initSetCaret = function() {
                var textObj = $(this).get(0);
                textObj.caretPos = document.selection.createRange().duplicate();
            };
            $(this)
                .click(initSetCaret)
                .select(initSetCaret)
                .keyup(initSetCaret);
        },
        /**
         * 在当前对象光标处插入指定的内容
         */
        insertAtCaret: function(textFeildValue) {
            var textObj = $(this).get(0);
            if (document.all && textObj.createTextRange && textObj.caretPos) {
                var caretPos = textObj.caretPos;
                caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == '' ? textFeildValue + '' : textFeildValue;
            } else if (textObj.setSelectionRange) {
                var rangeStart = textObj.selectionStart;
                var rangeEnd = textObj.selectionEnd;
                var tempStr1 = textObj.value.substring(0, rangeStart);
                var tempStr2 = textObj.value.substring(rangeEnd);
                textObj.value = tempStr1 + textFeildValue + tempStr2;
                textObj.focus();
                var len = textFeildValue.length;
                textObj.setSelectionRange(rangeStart + len, rangeStart + len);
                textObj.blur();
            } else {
                textObj.value += textFeildValue;
            }
        }
    });









});
